<?php

// +----------------------------------------------------------------------
// | 私信
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\event\index;

use app\common\event\Base;
use app\event\ucenter\MemberInfo;
use app\model\ucenter\User as UserModel;
use app\model\ucenter\UserMoneyLog as UserMoneyLogModel;
use app\model\index\CreditcardProduct as CreditcardProductModel;
use app\model\index\Order as OrderModel;
use app\model\index\CreditcardOrder as CreditcardOrderModel;
use app\model\ucenter\UserTask as UserTaskModel;
use app\event\ucenter\User as UserEvent;
use think\Exception;
use think\facade\Db;
use think\facade\Log;

class Task extends Base
{


    /**
     * 新增任务
     */
    public function add($param, $user)
    {
        try {

            $validate = \think\facade\Validate::rule([
                'real_name|姓名' => 'require|chs|max:25',
                'mobile|手机' => 'require|mobile',
                'idcard_no|身份证' => 'require|idCard'
            ]);

            if (!$validate->check($param)) {
                throw new Exception($validate->getError());
            }
            if (!$user) {
                if (empty($param['share_code'])) {
                    throw new Exception('数据异常');
                }
                if (false !== strpos(strtolower($param['share_code']), 'f')) {
                    $param['share_code'] = str_replace('f', '', strtolower($param['share_code']));
                }
                $user = UserModel::where('shareCode', $param['share_code'])->find();
            }
            //根据id获取产品详情
            $productInfo = CreditCardProductModel::where('id', $param['product_id'])->find();
            if (!$productInfo) {
                throw new Exception('此产品暂时无法申请');
            }
//            if(cache('order_'.$this->auth->id)){
//                $this->error('操作频繁，请稍后');
//            }
//            cache('order_'.$this->auth->id,true,2);
            $channel = '';
            if ($productInfo['settlementType'] == 2) {
                $goodUrl = $productInfo['product_url'];
            } else {
                $res = self::orderApi($productInfo['bankName'], $param['real_name'], $param['idcard_no'], $param['mobile']);
                if (strtolower($res->message) != 'success') {
                    if ($res->message == 'Good Is Null' || $res->message == 'Good No Sale') {
                        $productInfo['status'] = 0;
                        $productInfo->save();
                        throw new Exception('此产品已下架', 5010);
                    } else {
                        throw new Exception($res->message, 5010);
                    }
                }
                $goodUrl = $res->goodUrl;
            }

            $creditOrder = CreditcardOrderModel::where('productId', $productInfo['id'])
                ->where('userName', $param['real_name'])
                ->where('userTel', $param['mobile'])
                ->where('userNumber', $param['idcard_no'])
                ->whereTime('create_time', '>', '-3 day')
                ->find();

            //防止重复提交
            Db::startTrans();
            if ($creditOrder) {
                $status = 3;
                $step = 99;
            } else {
                $status = 0;
                $step = 0;
            }
            $task_insert = [
                'user_id' => $user ? $user['id'] : 0,
                'agent_id' => $user ? $user['agent_id'] : 0,
                'step' => $step,
                'status' => $status,
                'title' => $productInfo['bankName'],
                'task_id' => $productInfo['id'],//改换mobile_task_id
                'submit_info' => $param,
                'task_type' => $productInfo['type'],
                'money' => $productInfo['commission'],
                'commission' => $productInfo['commission'],
                'relation_id' => $param['product_id']
            ];
            $task = UserTaskModel::create($task_insert);
            if (!$task) {
                throw new Exception('系统故障');
            }

            $credit = [
                'user_id' => $user ? $user['id'] : 0,
                'user_task_id' => $task['id'],
                'productId' => $productInfo['id'],
                'productName' => $productInfo['bankName'],
                'settlement_type' => $productInfo['settlementType'],
                'type' => $productInfo['type'],
                'userName' => $param['real_name'],
                'userTel' => $param['mobile'],
                'api_status' => $step,
                'userNumber' => $param['idcard_no'],
            ];
            $creditOrder = CreditcardOrderModel::create($credit);
            if (!$creditOrder) {
                throw new Exception('系统故障2');
            }
            Db::commit();
            $data['code'] = 0;
            $data['data']['url'] = $goodUrl;
            $data['data']['info'] = $productInfo;
            $data['data']['credit'] = $creditOrder;
            $data['data']['task'] = $task;
            $data['message'] = 'ok';
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $data['code'] = 2;
            $data['message'] = $e->getMessage();
            $data['debug'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
//				$data['message'] = $e->getMessage();
        }
        return $data;
    }


    public function restart()
    {
        $credit_order = CreditcardOrderModel::where('id', 4016)->find();
        $order = OrderModel::where('id', 4753)->find();
        if (!$order) {
            throw new Exception('订单不存在');
        }
        $task = UserTaskModel::where('id', $credit_order['user_task_id'])->find();
        if (!$task) {
            throw new Exception('任务不存在');
        }
        $order['amount'] = 0;
        $order['status'] = 3;
        $order['auditTime'] = time();
//            $order->save();
        if (!in_array($task['status'], [0, 1])) {
            // 已经结束任务
            throw new Exception('任务已结束');
        }
        $money = $task['money'];
        if ($task['task_type'] == 2) { //贷款
            $product = Db::name('creditcard_product')->where('id', $credit_order['productId'])->find();
            if ($product['commission_type'] == 1) {
                $money = $credit_order['amount'] * $task['money'] / 100;
            }
        }
        $user = UserModel::where('id', $task['user_id'])->find();
        $userLevel = Db::name('member_info')->where('type', 'in', [1, $user['level']])->where('id', '<', 5)->order('type DESC')->find();
        $order['commission'] = $money * $userLevel['fee'];
        $order['points'] = (int)$money * $userLevel['fee'];
        if (!$order->save()) {
            throw new Exception('订单保存失败');
        }

        $task['commission'] = $money * $userLevel['fee'];
        $task['step'] = 2;
        $task['status'] = 2;
        if (!$task->save()) {
            throw new Exception('任务保存失败');
        }

        UserEvent::exhibitionIncome($user, $money, $credit_order['productName'], 11, $user['id'], $task['task_no'], 0, '', 1);

//            UserEvent::money($task['commission'], $task['user_id'], $credit_order['productName'], 11, $task['user_id'], $task['task_no'],0,'',1);
        UserEvent::score((int)$task['commission'], $task['user_id'], $credit_order['productName'], 11, $task['user_id'], $task['task_no']);

        // 代理
    }

    protected function _deal()
    {

    }

    /**
     *  信用卡回调
     *  'Phone' => Phone,
     * 'Bank' => ,
     * 'InviterPhone' => ,
     * 'Name' => ,
     * 'IdCard' => ,
     * 'Amount' => ,
     */
    public function third($param)
    {
        try {

            $credit_order = CreditcardOrderModel::where('userNumber', $param['IdCard'])
                ->where('userTel', $param['Phone'])
                ->where('userName', $param['Name'])
                ->where('productName', $param['Bank'])
                ->where('api_status', '<>', 10)
                ->where('status', 1)
                ->order('id desc')
                ->find();
            if (!$credit_order) {
                throw new Exception('订单不存在');
            }
            if ($credit_order['api_status'] == $param['Status']) {
                throw new Exception('状态未变更');
            }
            /**
             * 访问 0
             * 通过 1
             * 未提交 3
             * 审核中 4
             * 待激活 5
             * 拒绝 6
             * 二卡 7
             * 已激活 8
             * 提交失败 10
             * 待首刷 11
             * 已注销 12
             * 无效 13
             * 降级通过20
             */

            $credit_order['api_status'] = $param['Status'];
            $credit_order['amount'] = $param['Amount'];
            if (!$credit_order->save()) {
                throw new Exception('申请记录保存失败');
            }
            $task = UserTaskModel::where('id', $credit_order['user_task_id'])->find();
            if (!$task) {
                throw new Exception('任务不存在');
            }
            Db::startTrans();

            $money = $task['money'];
            if ($task['task_type'] == 2) { //贷款
                $product = Db::name('creditcard_product')->where('id', $credit_order['productId'])->find();
                if ($product['commission_type'] == 1) {
                    $money = $credit_order['amount'] * $task['money'] / 100;
                }
            }
            $user = UserModel::where('id', $task['user_id'])->find();
            $userLevel = Db::name('member_info')->where('type', 'in', [1, $user['level']])->where('id', '<', 5)->order('type DESC')->find();

            $task['step'] = $credit_order['api_status'];
            if (in_array($task['step'], [4, 5, 11, 8])) {
                $task['status'] = 1;
            } elseif ($task['step'] == 1) {
                $task['status'] = 2;
            } elseif ($task['step'] == 0) {
                $task['status'] = 0;
            } elseif (in_array($task['step'], [6, 7, 10, 13, 20, 12])) {
                $task['status'] = 3;
            } else {
                $task['status'] = 3;
            }
            $task['commission'] = $money * $userLevel['fee'];

            if (!$task->save()) {
                throw new Exception('任务保存失败');
            }
            if ($task['status'] == 2) {
                UserEvent::exhibitionIncome($user, $money, $credit_order['productName'], 11, $user['id'], $task['task_no'], 0, '', 1);

            }
            Db::commit();
            $data['code'] = 0;
            $data['message'] = 'ok';
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $data['code'] = 2;
            $data['message'] = $e->getMessage();
//            $data['debug'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
//				$data['message'] = $e->getMessage();
        }
        return $data;
    }

    //微支付API
    protected static function orderApi($bank, $userName, $idCard, $phone)
    {
        $param = [
            'Phone' => $phone,
            'Bank' => $bank,
            'InviterPhone' => '20200918018',
            'Name' => $userName,
            'IdCard' => $idCard,
        ];
        $url = 'https://admin.zzjgsw.com/api/apply';
        //初始化
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //不打印输出到页面中
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($ch);
        curl_close($ch);
        return json_decode($data);
    }

}
